#include "database.h"
#include "exceptions.h"
#include "filecache.h"
#include "schema.h"
#include "table.h"

#include <boost/filesystem.hpp>

namespace Database
{

using namespace boost::filesystem;

Schema::Schema()
{
    // Look for databases
    // TODO - move this into config
    const auto p = path("data");

    if(!exists(p) || !is_directory(p))
        throw EBadDataDir();

    for(auto it = directory_iterator(p); it != directory_iterator(); ++it)
    {
        const string db = basename(*it);
        if(databases_.find(db) != databases_.end())
            throw EDatabaseDuplicateName();

        databases_[db] = new Database(it->path().string());
    }

    // do stuff....
//    Table t("table1");
	/*
		FileCache fc(1048576, 16384);
	//	char buffer[200];

		fc.acquire("data/data1");
		fc.acquire("data/data1");

	//	fc.file("data/data1").read(30000, 200, buffer);

		fc.release("data/data1");
		fc.release("data/data1");
	*/

}


Schema::~Schema()
{
    for(auto entry : databases_)
        delete entry.second;
}


Database& Schema::database(const string& name)
{
    const auto it = databases_.find(name);
    if(it == databases_.end())
        throw EDatabaseNotFound();

    return *it->second;
}

}   // namespace Database
